﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceApplication.Dao.WorkFlow;
using CommonLibrary.DataModel.WorkFlow;
using ServiceApplication.Service;
using CommonLibrary.DataModel.Form;
using ServiceApplication.Service.WorkFlow;
using System.Xml.Linq;
using CommonLibrary.Common;
using Bukovics.Workflow.Hosting;
using System.Workflow.Activities;
using System.Data;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Service.Basic;
using CommonLibrary.Wf.InterFace;
using System.Transactions;

namespace AspWebTest
{
    public partial class WfProcess : System.Web.UI.Page
    {
        string taskid;
        string ptaskid;
        string formdefine;
        //int[] nextClr ;   //小马,选择的下一步处理人
        //WfClrxxInfo nextClrInfo=new WfClrxxInfo();
        FormService formService = new FormService();
        WorkFlowService workFlowService = new WorkFlowService();
        SerializeDesigner designer = new SerializeDesigner();
        BasicService basicService = new BasicService();
        FormEntity formEntity;
        List<WfInsvalueEntity> wfInsvalueEntitys;
        WfTaskEntity wfTaskEntity;

        protected void Page_Load(object sender, EventArgs e)
        {
            InitTree();
            taskid = Request.QueryString["taskid"].ToString();
            ptaskid = Request.QueryString["ptaskid"].ToString();
            txtGUID.Text = Request.QueryString["uniqueid"].ToString();
            wfTaskEntity = TaskDao.Query(taskid);
            formEntity = formService.QueryFormEntityByWfinsId(wfTaskEntity.uniqueid.ToString());
            wfInsvalueEntitys = workFlowService.QueryInsvalue(ptaskid);

            if (!IsPostBack)
            {
                Button_refresh_Click(null, null);
            }

            if (formEntity != null)
            {
                XElement xml = XElement.Load(Server.MapPath("~/uploads/" + formEntity.location));
                xml = designer.FillInsValueToXml(xml, wfInsvalueEntitys);
                formdefine = designer.DeserializeXmlToWeb(xml);
            }
        }
        protected void Button_oksend_Click(object sender, EventArgs e)
        {
            string s = txtGUID.Text.Trim();
            if (s.Length > 0 && DropDownList1.SelectedValue != "-1")
            {
                string nid = DropDownList1.SelectedValue;
                Guid instanceId = new Guid(s);

                BillServer billserver = ((Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager)
                    .WorkflowRuntime).GetService<ServiceApplication.Service.WorkFlow.BillServer>();
                ManualWorkflowSchedulerService scheduler = (Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager)
                    .WorkflowRuntime.GetService<ManualWorkflowSchedulerService>();

                StateMachineWorkflowInstance stateInstance = new StateMachineWorkflowInstance(
                    (Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager).WorkflowRuntime, instanceId);
                EventDrivenActivity edact = (EventDrivenActivity)stateInstance.CurrentState.Activities[nid];
                HandleExternalEventActivity heva = (HandleExternalEventActivity)edact.EnabledActivities[0];

                WfEntity wfEntity = workFlowService.QueryWfByuniqueid(s);
                WfClrxxInfo nextClrInfo = workFlowService.getNextClrxxByTaskName(
                    (Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>),
                    wfEntity.wftemplate_id, edact.Parent.Name, DropDownList1.SelectedItem.Text);
                #region 数据获取: 表单值wivList
                List<FormFieldEntity> ffeList = new FormService().QueryFormFieldEntitys(formEntity.form_id, "text");
                List<WfInsvalueEntity> wivList = new List<WfInsvalueEntity>();
                //Dictionary<string,object> 
                foreach (FormFieldEntity item in ffeList)
                {
                    wivList.Add(new WfInsvalueEntity()
                    {
                        task_id = int.Parse(taskid),
                        fieldName = item.name,
                        fieldType = item.fieldtype,
                        fieldValue = Request.Form[item.name]
                    });
                }
                #endregion

                #region 如果tree可见,获取页面上选择的下一步处理人,如果不可见，则在当页初始化的时候已赋值
                if (TreeView1.Visible == true)
                {
                    TreeNodeCollection nexts = TreeView1.CheckedNodes;
                    if (TreeView1.CheckedNodes.Count == 0)
                    {
                        MessageBox.Show(this, "请选择处理人");
                        return;
                    }
                    nextClrInfo.clrCode = new int[nexts.Count];
                    for (int i = 0; i < nexts.Count; i++)
                    {
                        UserEntity nextOne = basicService.QueryUser(int.Parse(nexts[i].Value));
                        if (nextOne.name != nexts[i].Text) MessageBox.Show(this, "出错：不存在" + nexts[i].Text);
                        nextClrInfo.clrCode[i] = nextOne.id;
                        nextClrInfo.clzType = TaskClrType.按人员.ToString();
                    }
                } //增加type="发起人"的处理  mlh  2011-11-21 待验证
                else
                {
                    if (nextClrInfo != null && nextClrInfo.clzType == TaskClrType.发起人.ToString())
                    {
                        nextClrInfo.clrCode = new int[1];
                        nextClrInfo.clrCode[0] = wfTaskEntity.fqrcode;
                    }
                }
                if (nextClrInfo == null) nextClrInfo = new WfClrxxInfo(); //如果是null，就初始化，下面 RaiseEvent 事件需要nextClrInfo.clr参数 mlh 2011-11-21 +
                #endregion
                #region 数据获取: 新任务实体taskEntityNew
                WfTaskEntity taskEntity = workFlowService.QueryTask(taskid);
                List<WfTaskEntity> taskEntityNewlist = new List<WfTaskEntity>();
                //如果nextClrInfo.clrCode==null 则说明下一步结束了,待验证 mlh 2011-11-21
                if (nextClrInfo.clrCode != null)
                {
                    for (int i = 0; i < nextClrInfo.clrCode.Length; i++)
                    {
                        taskEntityNewlist.Add(new WfTaskEntity()
                        {
                            ptask_id = int.Parse(taskid),//新任务中的ptaskid即是正在处理的任务的taskid
                            uniqueid = new Guid(txtGUID.Text),
                            taskname = edact.Parent.Name,//这里还要看看!!!!
                            state = WfTaskState.TASK_UNDO,
                            processresult = "",
                            processtype = nextClrInfo.clzType,
                            processaddition = "无",
                            user_id = nextClrInfo.clrCode[i],
                            fqrcode = taskEntity.fqrcode,
                            task_id = int.Parse(taskid),
                            starttime = taskEntity.starttime,
                            checkintime = DateUtil.getStandardTimeBySecond(),
                            days = 100,
                            senttime = DateUtil.getStandardTimeBySecond()  //mlh 2011-11-21 + 原因：未赋值，待验证
                        });
                    }
                }
                #endregion
                #region 事务操作: 添加数据库,触发工作流
                TransactionOptions option = new TransactionOptions();
                option.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option))
                {
                    try
                    {
                        workFlowService.UpdateTask(taskid, ptaskid, new Guid(txtGUID.Text), null);//mlh 2012-03-07 增加最后一个参数
                        workFlowService.AddTask(taskEntityNewlist);
                        workFlowService.addInsvalue(wivList);
                        billserver.RaiseEvent(heva.EventName, new ReceivedEventArgs(instanceId,
                            Application[MyWorkHelpr.UserEntity] as UserEntity, nextClrInfo.clrCode, "taskname", wivList));
                        scope.Complete();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                #endregion
                MessageBox.Show(this, "处理结束");
            }
        }
        protected void Button_cancel_Click(object sender, EventArgs e)
        {

        }
        protected void Button_refresh_Click(object sender, EventArgs e)
        {
            string s = txtGUID.Text.Trim();
            if (s.Length > 0)
            {
                DropDownList1.DataValueField = "NID";
                DropDownList1.DataTextField = "NTEXT";
                DropDownList1.DataSource = getNextStep(s);
                DropDownList1.DataBind();
            }
        }

        private DataTable getNextStep(string s)
        {
            Guid instanceId = new Guid(s);
            StateMachineWorkflowInstance stateInstance = new StateMachineWorkflowInstance(
                (Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager).WorkflowRuntime, instanceId);
            DataTable dt = new DataTable();
            dt.Columns.Add("NID", typeof(string));
            dt.Columns.Add("NTEXT", typeof(string));
            dt.Rows.Add("-1", "==请选择==");
            int i = 0;
            foreach (Activity act in stateInstance.CurrentState.EnabledActivities)
            {

                if (act is EventDrivenActivity)
                {
                    EventDrivenActivity edact = (EventDrivenActivity)act;

                    if (edact.EnabledActivities.Count > 0 && edact.EnabledActivities[0] is HandleExternalEventActivity)
                    {
                        dt.Rows.Add(edact.Name, act.Description);
                    }
                }
                i++;
            }
            return dt;
        }

        public string getDefine()
        {
            return formdefine;
        }
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //判断是否处理人类型
            string nid = DropDownList1.SelectedValue;
            if (nid == "-1") return;
            Guid instanceId = new Guid(txtGUID.Text);

            StateMachineWorkflowInstance stateInstance = new StateMachineWorkflowInstance(
                (Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager).WorkflowRuntime, instanceId);
            EventDrivenActivity edact = (EventDrivenActivity)stateInstance.CurrentState.Activities[nid];

            WfEntity wfEntity = workFlowService.QueryWfByuniqueid(txtGUID.Text);
            WfClrxxInfo clrxx = workFlowService.getNextClrxxByTaskName(
                (Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>),
                wfEntity.wftemplate_id, edact.Parent.Name, DropDownList1.SelectedItem.Text);

            if (clrxx == null)
            {
                TreeView1.Visible = false;
            }
            else
            {
                if (clrxx.clzType == TaskClrType.由上一步处理人指定.ToString())
                {
                    TreeView1.Visible = true;
                }
                else
                {
                    TreeView1.Visible = false;
                }
            }
        }

        #region tree
        private void InitTree()
        {
            TreeView1.ShowCheckBoxes = TreeNodeTypes.Leaf;

            DataTable dt = basicService.QueryAllDepts();
            WebNodeHelp nh = new WebNodeHelp(dt, "部门编码", "部门名称", "上级编码", "部门编码=1");

            //将子node写入treeview
            foreach (var item in basicService.GetWebUserNodeList())
            {
                TreeView1.Nodes.Add(item);
            }
        }
        #endregion
    }
}
